package remote

import (
	"github.com/go-resty/resty/v2"
	"github.com/shirou/gopsutil/cpu"
	"github.com/shirou/gopsutil/host"
	"github.com/shirou/gopsutil/mem"
	"net/url"
	"os"
	"runtime"
	"time"
	"wf-deploy-agent/conf"
	"wf-deploy-agent/consts"
	"wf-deploy-agent/infra"
	"wf-deploy-agent/registry"
	"wf-deploy-agent/remote/entity"
)

var Api = NewScheduler()

func NewScheduler() *Scheduler {
	scheduler := &Scheduler{&Proxy{}}
	scheduler.client = resty.New()
	scheduler.client.SetRetryCount(3)
	scheduler.serviceName = conf.CF.Scheduler.Name
	return scheduler
}

type Scheduler struct {
	*Proxy
}

func (s *Scheduler) FetchPluginSummary() []*entity.PluginInfo {
	result := &entity.FetchPluginResponse{}
	_, err := s.post(s.concatUrl(consts.SchedulerApiPrefix+"/plugin/summary"), &entity.FetchPluginRequest{
		Platform: runtime.GOOS,
		Arch:     runtime.GOARCH,
	}, result)
	if err != nil {
		infra.Logger.Errorln(err)
	}

	return result.Data
}

func (s *Scheduler) Heartbeat() {
	hostname, err := os.Hostname()
	if err != nil {
		return
	}

	platform, _, version, err := host.PlatformInformation()
	if err != nil {
		return
	}

	memory, err := mem.VirtualMemory()
	if err != nil {
		return
	}

	logicalCpuCount, err := cpu.Counts(true)
	if err != nil {
		return
	}

	_, err = s.post(s.concatUrl(consts.SchedulerApiPrefix+"/cluster/agent/heartbeat"), &entity.Heartbeat{
		HostName:        hostname,
		Identity:        conf.CF.Agent.Identity,
		AgentState:      consts.AgentInstalled,
		AgentVersion:    conf.CF.Agent.Version,
		Arch:            runtime.GOARCH,
		Kernel:          runtime.GOOS,
		Platform:        platform,
		PlatformVersion: version,
		HeartbeatTime:   time.Now().UnixMilli(),
		MemoryTotal:     memory.Total,
		MemoryAvailable: memory.Available,
		LogicalCpuCount: logicalCpuCount,
	}, nil)

	if err != nil {
		infra.Logger.Errorln(err)
	}
}

func GetPluginDownloadUrl(plugin *entity.PluginInfo) string {
	instance := registry.GetRepository().GetInstance("plugin")
	if instance == nil {
		return ""
	}

	result, err := url.JoinPath(instance.GetHttpPrefix(), plugin.RelativePath)
	if err != nil {
		return ""
	}

	return result
}
